<?php
class Admin_LoginController extends Ctrl_Base{

	public function indexAction(){
            
            /*if(isset($_COOKIE['admin'])){
            $tMO = new AdminModel;
            $pName = empty($_COOKIE['admin']['name'])?Tool_Fnc::ajaxMsg('未知错误'):Tool_Fnc::safe_string($_COOKIE['admin']['name']);
            $pId = empty($_COOKIE['admin']['id'])?Tool::ajaxMsg('未知错误'):intval($_COOKIE['admin']['id']);
            $tRow = $tMO->field('*')->where("id = {$pId} and name = '{$pName}'")->fRow();
            $_SESSION['admin'] = array('id'=> $tRow['id'],'name' => $tRow['name']);
            }*/

        if(isset($_SESSION['admin'])){$this->showMsg('','/admin_index/');}
	}

    public function loginAction(){
		//if(!$this->valiCaptcha()) return;
        $p = $_REQUEST; 
        $pName = empty($p['name'])?Tool_Fnc::ajaxMsg('用户名不能为空'):Tool_Fnc::safe_string($p['name']);
        $pPasswd = empty($p['passwd'])?Tool_Fnc::ajaxMsg('密码不能为空'):trim($p['passwd']);
        //$pCaptcha = empty($p['captcha'])?Tool_Fnc::ajaxMsg('验证码为空'):trim($p['captcha']);

        $tMO = new AdminModel;
        $tRow = $tMO->field('*')->where("name = '{$pName}'")->fRow();

        if(!count($tRow)){Tool_Fnc::ajaxMsg('用户不存在');}
        if(Tool_Fnc::markmd5($pPasswd,$tRow['private_key']) != $tRow['passwd']){Tool_Fnc::ajaxMsg('密码不正确'); }

        $_SESSION['admin'] = array('id'=> $tRow['id'],'name' => $tRow['name'],'roles' => $tRow['role']);

        $tPMO = new PermissionModel;
        $tPData = $tPMO->field('permission')->where('role = '.$tRow['role'])->fRow();

        $_SESSION['admin']['role'] = explode(',',$tPData['permission']);

        setcookie('admin[roles]',$tRow['role'],time()+3600*24,'/');
            setcookie('admin[id]',$tRow['id'],time()+60*60*24*365,'/');
            setcookie('admin[name]',$tRow['name'],time()+60*60*24*365,'/');
            setcookie('admin[role]',$tPData['permission'],time()+60*60*24*365,'/');

        if(isset($p['remember']) && $p['remember'] == 'remember'){
            setcookie('admin[id]',$tRow['id'],time()+60*60*24*365,'/');
            setcookie('admin[name]',$tRow['name'],time()+60*60*24*365,'/');
            setcookie('admin[roles]',$tRow['role'],time()+60*60*24*365,'/');
            setcookie('admin[role]',$tPData['permission'],time()+60*60*24*365,'/');
        }

		$this->showMsg('', '/admin_index');
        Tool_Fnc::ajaxMsg('',1);
    }

    public function quitAction(){
        session_destroy();
        setcookie('admin[id]','',time()-1,'/');
        setcookie('admin[name]','',time()-1,'/');
        unset($_COOKIE);
		$this->showMsg('', '/admin_login');
    }
	/**
	 * 验证码
	 */
	public function captchaAction(){
		$captcha = new Tool_Captcha(80, 35, 4);
		$captcha->showImg();
        exit;
	}
	
}
